﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SQLHelper;
using MessageBoxHelper;

namespace BBS
{
    public partial class RegisterPage : BasePage
    {
        private bool isPickNameRepeat;
        protected void Page_Load (object sender, EventArgs e)
        {
            if ( !IsPostBack )
            {
                this.isPickNameRepeat = false;
            }
        }

        protected void btnRegister_Click (object sender, EventArgs e)
        {
            string pickName = this.txtPickName.Text;
            string pwd = this.txtPwd.Text;

            int limit = 2;  //用户默认权限为普通用户

            this.isPickNameRepeat = false;

            //先判断该用户名是否已被使用
            string judgeRepeatStr = string.Format("SELECT COUNT(ACCOUNT_ID) FROM ACCOUNT WHERE PICKNAME='{0}';", pickName);
            SQLHelperSingleton.TryExecuteScalar(judgeRepeatStr, this.JudgePickNameIsRepeat, this.Fail);

            if ( this.isPickNameRepeat == true )
            {
                return;
            }

            //如果用户名没有被使用，即可创建新用户
            string insertStr = string.Format("INSERT INTO ACCOUNT(PICKNAME,PWD,LIMIT) VALUES('{0}','{1}',{2});", pickName, pwd, limit);
            SQLHelperSingleton.TryExecuteNonQuery(insertStr, this.Fail);

            this.ExecuteJS("alert('用户注册成功!');window.location.href='Login.aspx';");
        }

        /// <summary>
        /// 判断昵称是否重复了
        /// </summary>
        /// <param name="count"></param>
        private void JudgePickNameIsRepeat (object count)
        {
            bool isRepeat = (int)count > 0;
            this.lblRepeat.Visible = isRepeat;
            this.isPickNameRepeat = isRepeat;
        }

        private void Fail (string err)
        {
            this.ExecuteJS(string.Format("alert('{0}');", err));
        }
    }
}